import { defineConfig } from 'vite'
import vueJsx from '@vitejs/plugin-vue-jsx'
import path from 'path'
import vue from '@vitejs/plugin-vue'

// const pathResolve = (dirPath) => path.resolve(process.cwd(), dirPath)

const libNameReg = /\/node_modules\/([^/]+)\//

const manualChunks = (id) => {
  if (libNameReg.test(id.toString())) {
    const libName = RegExp.$1
    switch (libName) {
      case '@vue':
      case 'echarts':
      case '@popperjs':
      case 'element-plus':
      case '@element-plus':
        return libName
      default:
        return 'vendor'
    }
  }
}

// https://vitejs.dev/config/
export default ({ command }) => {
  return defineConfig({
    plugins: [
      vue(),
      vueJsx(), // 文档 https://github.com/vuejs/babel-plugin-jsx/blob/dev/packages/babel-plugin-jsx/README-zh_CN.md
    ],
    // resolve: {
    //   alias: [
    //     {
    //       find: /\/@\//,
    //       replacement: `${pathResolve('src')}/`,
    //     },
    //   ],
    // },
    resolve: {
      alias: {
        // 别名 `@` 指向 `src` 目录 PS:IDEA编辑器还是不能识别
        '@': path.resolve(__dirname, 'src'),
        assets: '/src/assets',
        comp: '/src/components',
      },
    },
    server: {
      port: 3000,
      proxy: {
        '/api': {
          target: 'http://10.88.212.126:32987',
          changeOrigin: true,
          rewrite: (p) => p.replace(/^\/api/, '/api'),
        },
      },
    },
    build: {
      reportCompressedSize: false, // 禁用 压缩大小报告,以提高大型项目的构建性能。
      // https://www.zhihu.com/question/518443897/answer/2397938046
      rollupOptions: { manualChunks },
    },
    esbuild: {
      jsxFactory: 'h',
      jsxFragment: 'Fragment',
    },
  })
}
